import React, { Component } from "react";
import { Form, Icon, Input, Button, message} from "antd";
import {Redirect} from "react-router-dom"
import {reqLogin} from "../../api"
import storeutil from "../../util/storeutil";
import "../login/login.css"
// import { Redirect } from "react-router";
class Login extends Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields(async(err, values) => {
      if (!err) {
        // console.log("Received values of form: ", values);
        const {username,password}=values
        console.log(username,password);
        const result=await reqLogin(username,password)
        console.log(result);
        if(result.status===0){
          const user=result.data
          storeutil.saveUser(user)
          message.success("登陆成功")
          this.props.history.push("/")
        }else{
          message.error(result.msg)
        }
      }
    });
  };
  render() {
    const user=storeutil.getUser()
    if(user&&user._id){
      return <Redirect to="/" />
    }
    const { getFieldDecorator } = this.props.form;
    return (
      <>
      <div className="login_content">
        <Form onSubmit={this.handleSubmit} className="login-form">
          <Form.Item>
            {getFieldDecorator("username", {
              rules: [
                { required: true, message: "请输入用户名" },
              ],
            })(
              <Input
                prefix={
                  <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                }
                placeholder="用户名"
              />
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator("password", {
              rules: [
                { required: true, message: "请输入密码" },
              ],
            })(
              <Input
                prefix={
                  <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                }
                type="password"
                placeholder="密码"
              />
            )}
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              登陆
            </Button>
          </Form.Item>
        </Form>
        </div>
      </>
    );
  }
}

export default Form.create()(Login);
